package com.learning.security.controller;

import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName VerifyCodeController
 * @Description TODO
 * @Author Jiangnan Cui
 * @Date 2022/8/11 23:06
 * @Version 1.0
 */
@RestController // 一定是RestController而非Controller
public class VerityCodeController {
    private final Producer producer;

    @Autowired
    public VerityCodeController(Producer producer) {
        this.producer = producer;
    }

    @GetMapping("/vc.jpg")
    public String getVerifyCode(HttpSession session) throws IOException {
        // 1.生成验证码
        String verifyCode = producer.createText();
        // 2.存入Session或Redis
        session.setAttribute("kaptcha", verifyCode);
        // 3.生成图片
        BufferedImage bi = producer.createImage(verifyCode);
        // 图片转化为字节
        FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
        ImageIO.write(bi, "jpg", fbaos);
        // 4.返回base64
        return Base64.encodeBase64String(fbaos.toByteArray());
    }
}